//
//  FilelistViewController.swift
//  Browser
//
//  Created by 鹏鹏 on 2021/7/4.
//

import UIKit
import MBProgressHUD

class FilelistViewController: BaseViewController {

    var currentPath: String = KFileManager.getFilesDirPath()

    var fileNameList: [FileListModel] = []

    var fileListView = FileListView(frame: CGRect.zero)

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        self.loadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupNavigationItem()
        self.setupViews()

        NotificationCenter.default.addObserver(self, selector: #selector(receivedNewFileNotice(_:)), name: KDefine.Notice.kNotificationNameReceivedNewFile, object: nil)

        self.loadData()
    }

    func setNavigationTitle(_ title: String) {
        self.navigationItem.title = title

        if self.navigationController?.viewControllers.count == 1 {
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "hammer"), style: .done, target: self, action: #selector(checkInboxFolder(_:)))
        }
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "delete"), style: .done, target: self, action: #selector(deleteFolder(_:)))
    }

    func setupNavigationItem() {

        self.setNavigationTitle((self.currentPath as NSString).lastPathComponent)
    }

    func setupViews() {

        fileListView.itemClickedClosure = { [weak self] (index, cell) in
            guard let fileModel = self?.fileNameList[index] else { return }
            guard let fileName = fileModel.fileName else { return }
            guard let currentPath = self?.currentPath else { return }

            let fileType = KFileManager.getFileType(withFileName: fileName)
            if fileType == .picture {

                self?.viewPhotos(fileName, cell)

            } else if fileType == .archive {

                KFileManager.unzipFile(atPath: currentPath + "/" + fileName, toDestinationDir: currentPath)

            } else if fileType == .folder || fileType == .other {

                let path = currentPath + "/" + fileName
                self?.viewSubFiles(path)
            }
        }
        fileListView.dataRefreshClosure = { [weak self] fileListView in
            self?.loadData()
        }
        self.view.addSubview(fileListView)
        fileListView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(self.view.snp_bottomMargin)
        }
    }

    func loadData(_ animated: Bool = true) {

        if animated {
            MBProgressHUD.showAdded(to: self.view, animated: true)
        }
        do {
            var fileNames = try KFileManager.default.contentsOfDirectory(atPath: self.currentPath)
            fileNames = KTools.sortArray(NSMutableArray(array: fileNames)) as? [String] ?? []

            self.fileNameList.removeAll()

            for fileName in fileNames {

                if fileName.count == 0 || fileName.starts(with: ".") {
                    continue
                }
                let fileModel = FileListModel()
                fileModel.fileName = fileName
                fileModel.isFolder = KFileManager.getFileType(withFileName: fileName) == .folder
//                fileModel.fileCount = try KFileManager.default.contentsOfDirectory(atPath: self.currentPath + "/" + fileName).count
                fileModel.fileSize = 0
                self.fileNameList.append(fileModel)
            }
            self.setNavigationTitle((self.currentPath as NSString).lastPathComponent + "(\(self.fileNameList.count))")
            self.fileListView.setData(list: self.fileNameList, dirPath: self.currentPath)

            if animated {
                MBProgressHUD.hide(for: self.view, animated: true)
            }
        } catch {
            if animated {
                MBProgressHUD.hide(for: self.view, animated: true)
            }
            Logger.printLog(error)
        }
    }

    func viewSubFiles(_ path: String) {
        let fileListVC = FilelistViewController()
        fileListVC.currentPath = path
        self.navigationController?.pushViewController(fileListVC, animated: true)
    }

    @objc func checkInboxFolder(_ sender: UIBarButtonItem) {

        let documentsPath = KFileManager.getDocumentDirPath()
        MBProgressHUD.showAdded(to: self.view, animated: true)
        do {
            var fileNames = try KFileManager.default.contentsOfDirectory(atPath: documentsPath)
            fileNames = KTools.sortArray(NSMutableArray(array: fileNames)) as? [String] ?? []
            for fileName in fileNames {

                if fileName.count == 0 || fileName.starts(with: ".") {
                    continue
                }

                if KFileManager.getFileType(withFileName: fileName) == .archive {

                    // 解压文件到
                    KFileManager.unzipFile(atPath: documentsPath + "/" + fileName)
                }
            }
            MBProgressHUD.hide(for: self.view, animated: true)
        } catch {
            MBProgressHUD.hide(for: self.view, animated: true)
            Logger.printLog(error)
        }

        let inboxPath = KFileManager.getInboxDirPath()
        MBProgressHUD.showAdded(to: self.view, animated: true)
        do {
            var fileNames = try KFileManager.default.contentsOfDirectory(atPath: inboxPath)
            fileNames = KTools.sortArray(NSMutableArray(array: fileNames)) as? [String] ?? []
            for fileName in fileNames {

                if fileName.count == 0 || fileName.starts(with: ".") {
                    continue
                }

                if KFileManager.getFileType(withFileName: fileName) == .archive {

                    // 解压文件到
                    KFileManager.unzipFile(atPath: inboxPath + "/" + fileName)
                }
            }
            MBProgressHUD.hide(for: self.view, animated: true)
        } catch {
            MBProgressHUD.hide(for: self.view, animated: true)
            Logger.printLog(error)
        }

    }

    @objc func deleteFolder(_ sernder: UIBarButtonItem) {

        self.showAlert(title: "删除文件夹", message: "该操作将删除当前文件夹, 请谨慎操作", cancelTitle: "我不删了", cancelAction: nil, confirmTitle: "删了吧") { action in

            MBProgressHUD.showAdded(to: self.view, animated: true)

            if self.currentPath != KFileManager.getFilesDirPath() {

                KFileManager.removeItem(atPath: self.currentPath)
                self.navigationController?.popViewController(animated: true)
            } else {

                KFileManager.removeItem(atPath: self.currentPath + "/.")
                self.loadData()
            }

            MBProgressHUD.hide(for: self.view, animated: true)
        }
    }
}

extension FilelistViewController {

    func viewPhotos(_ fileName: String, _ cell: FileListViewCell) {

        var currentPage = 0
        var imageList: [YBIBImageData] = []
        for index in 0..<self.fileNameList.count {
            let fileNameTemp = self.fileNameList[index].fileName ?? ""
            if KFileManager.getFileType(withFileName: fileNameTemp) != .picture {
                continue
            }
            if fileName == fileNameTemp {
                currentPage = imageList.count
            }
            let data = YBIBImageData()
            data.imagePath = self.currentPath + "/" + fileNameTemp
            data.projectiveView = cell.imageView
            imageList.append(data)
        }

        let browser = YBImageBrowser()
        browser.delegate = self
        browser.dataSourceArray = imageList
        browser.currentPage = currentPage
        browser.supportedOrientations = .portrait
        let handler = PicBrowserToolViewHandler()
        browser.toolViewHandlers = [handler]
        browser.show()
    }
}

extension FilelistViewController {

    @objc func receivedNewFileNotice(_ notice: Notification) {

        self.showAlert(title: "提示", message: "检测到文件变更, 是否立即刷新?", cancelTitle: "不用", cancelAction: nil, confirmTitle: "刷新") { action in
            let date = notice.userInfo
            guard let fileName = date?["name"] else { return }
            guard let filePath = date?["path"] as? String else { return }
    //        if self.navigationController?.viewControllers.count == 1 {
            if filePath.contains(self.currentPath) {
                Logger.printLog("检测到添加新文件\(fileName), 自动刷新")
                self.loadData()
            }
        }
    }
}

extension FilelistViewController: YBImageBrowserDelegate {

    func yb_imageBrowser(_ imageBrowser: YBImageBrowser, pageChanged page: Int, data: YBIBDataProtocol) {
        let indexPath = IndexPath(item: page, section: 0)
        self.fileListView.collectionView .scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
        let data = data as! YBIBImageData
        let cell = self.fileListView.collectionView.cellForItem(at: indexPath) as! FileListViewCell
        data.projectiveView = cell.imageView
    }
}
